#!/bin/sh

file=$1
w=`expr $2 - 1`
h=$3
x=$4
y=$5

conf_path=$HOME/.config/lf

kitty_icat() {
  kitty +icat --silent --transfer-mode file --place "${w}x${h}@${x}x${y}" "${1}"
}

text_preview() {
  bat --color=always --style=numbers,changes --line-range=:"${h}" "${1}" \
      || highlight -O truecolor -s molokai --force -l --line-range=1-"${h}" "${1}" \
      || cat "${1}"
}

get_mime_type() {
  file --dereference --brief --mime-type "${1}"
}

case "$file" in
  *.md) glow -s dark "$file";;
  *.tgz|*.tar.gz) tar tzf "$file";;
  *.tar.bz2|*.tbz2) tar tjf "$file";;
  *.tar.txz|*.txz) xz --list "$file";;
  *.tar) tar tf "$file";;
  *.zip|*.jar|*.war|*.ear|*.oxt) unzip -l "$file";;
  *.rar) unrar l "$file";;
  *.7z) 7z l "$file";;
  *.[1-8]) man "$file" | col -b ;;
  *.o) nm "$file" | less ;;
  *.torrent) transmission-show "$file";;
  *odt,*.ods,*.odp,*.sxw) odt2txt "$file";;
  *.doc) antiword "$file" ;;
  *.docx) docx2txt.pl "$file" - ;;
  .xls) xls2csv "$file";;
  *.xlsx) xlsx2csv "$file";;
  *.csv) cat "$file" | sed s/,/\\n/g ;;
  *.pdf) pdftotext -l 10 -nopgbrk -q "$file" -;;
  *.bmp|*.jpg|*.jpeg|*.png|*.xpm) kitty_icat "$file" && exit 1;;
  *.wav|*.mp3|*.flac|*.m4a|*.wma|*.ape|*.ac3|*.og[agx]|*.spx|*.opus|*.as[fx]|*.flac) mediainfo "$file";;
  *.avi|*.mp4|*.wmv|*.dat|*.3gp|*.ogv|*.mkv|*.mpg|*.mpeg|*.vob|*.fl[icv]|*.m2v|*.mov|*.webm|*.mts|*.m4v|*.r[am]|*.qt|*.divx)
    kitty_icat "$($conf_path/vidthumb "$file")" && exit 1 || mediainfo "$file";;
  *.ts) [[ $(get_mime_type "$file") == text/* ]] && text_preview "$file" || kitty_icat "$($conf_path/vidthumb "$file")" && exit 1 || mediainfo "$file";;
  *.json) jq --color-output . "$file" || bat --color=always --style=numbers,changes --line-range=:"$3" "$file";;
  *) text_preview "$file";;
esac
